Popular Searches
Popular Course Categories
Popular Courses

Creating a React Application

Creating a React Application

React Project Setup

Creating a React Application – Detailed Notes

Creating a React application means setting up a project where React components are used to build interactive user interfaces. React applications can be used to develop websites, dashboards, e-commerce platforms, social media interfaces, and many other web applications.

Course: JustAcademy React JS Training

Course Demo: Register for React JS Course Demo


1. What Is a React Application?

A React application is a user interface application built using React, a JavaScript library for creating component-based interfaces. A React application is divided into reusable components that describe different parts of the user interface.

For example, an e-commerce application may contain the following components:

  • Header: Displays the logo, navigation links, and search bar.
  • Navbar: Provides navigation between different pages or sections.
  • ProductList: Displays available products.
  • ProductCard: Shows individual product details.
  • ShoppingCart: Displays selected products.
  • Footer: Displays contact information and other links.

Example

function App() {
  return (
    <div>
      <h1>My First React Application</h1>
      <p>Welcome to React JS!</p>
    </div>
  );
}
export default App;

In this example, the App component returns JSX that describes the user interface.


2. Requirements for Creating a React Application

Before creating a React application on your computer, prepare the following tools.

Tool Purpose
HTML Provides the basic structure of web pages.
CSS Controls the visual appearance and layout.
JavaScript Provides programming logic and interactivity.
Node.js Provides a JavaScript runtime used by development tools.
npm Installs and manages project dependencies.
Code editor Allows you to write and edit React code; Visual Studio Code is one common option.
Web browser Runs and displays the application.
Vite Provides a development server and build tools for a React project.

Check Node.js and npm

Open Command Prompt or a terminal and run these commands:

node -v
npm -v

If both commands display version numbers, Node.js and npm are available in your terminal. If they are not recognized, install Node.js from its official website and reopen the terminal.

Download Node.js


3. Create a React Application Using Vite

Vite is a modern frontend build tool that helps developers create and run React projects. For learning React from scratch, Vite is a common starting option.

React's official documentation recommends considering a React framework for many new production applications. A Vite setup is useful when you want to learn the fundamentals or build a client-side React application with your own tool choices. Read the official React guide.

Step 1: Open the Terminal

Open Command Prompt, PowerShell, or the integrated terminal in Visual Studio Code.

Step 2: Create the Project

Run the following command:

npm create vite@latest my-react-app -- --template react

Explanation:

  • npm create vite@latest runs the latest Vite project generator.
  • my-react-app is the name of the new project folder.
  • --template react selects the React JavaScript template.

You can replace my-react-app with your preferred project name.

Step 3: Open the Project Folder

cd my-react-app

This command moves the terminal into your newly created React project.

Step 4: Install Dependencies

npm install

This command installs the packages listed in the project's configuration files.

Step 5: Start the Development Server

npm run dev

The terminal displays a local URL, often http://localhost:5173/. Open the exact URL shown in your terminal in a browser.

Step 6: Start Coding

Open the project folder in your code editor. Locate src/App.jsx and modify the component to display your own content.

Official reference: Vite Getting Started Guide.


4. React Application Creation Flow

Install Node.js
      |
      v
Verify Node.js and npm
      |
      v
Create React Project with Vite
      |
      v
Open Project Folder
      |
      v
Install Dependencies
      |
      v
Write React Components
      |
      v
Start Development Server
      |
      v
Open Application in Browser
      |
      v
Test and Improve the UI
      |
      v
Build for Production

5. Understanding the React Project Structure

After creating a React application with Vite, the project contains several files and folders. A typical structure looks like this:

my-react-app/
├── node_modules/
├── public/
│   └── vite.svg
├── src/
│   ├── assets/
│   ├── App.css
│   ├── App.jsx
│   ├── index.css
│   └── main.jsx
├── index.html
├── package.json
├── package-lock.json
├── vite.config.js
└── .gitignore
File or Folder Description
node_modules/ Contains installed project dependencies. It is generated by the package manager.
public/ Contains static files served as-is, such as icons or images.
src/ Contains the main application source code.
src/App.jsx Contains the main App component in a typical starter project.
src/App.css Contains styles for the App component when imported.
src/index.css Often contains global styles for the application.
src/main.jsx Entry point that renders the React application into the HTML page.
index.html HTML page that contains the element where React mounts.
package.json Stores project metadata, dependencies, and scripts.
package-lock.json Records the dependency tree for npm installations.
vite.config.js Contains optional Vite configuration.
.gitignore Lists files and folders Git should ignore.

The exact structure may vary depending on the template and tools you select.


6. Understanding the main.jsx File

The main.jsx file is usually the entry point for a Vite React application. It imports React-related functions and renders the main App component inside an HTML element.

Example of main.jsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
import "./index.css";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

Explanation

  • StrictMode enables additional development checks for certain React issues.
  • createRoot creates a React root for rendering into a DOM element.
  • document.getElementById("root") selects the HTML element where React will render.
  • renders the main App component.
  • index.css imports global CSS styles.

7. Understanding the index.html File

The index.html file provides the base HTML document for the Vite application. It includes the element where React mounts and loads the JavaScript entry point.

Example

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My React App</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

The root element is the mounting point for the React application in this example. The JavaScript entry point imports and renders the App component.


8. Create Your First React Component

Open src/App.jsx and replace its content with the following code:

function App() {
  return (
    <div>
      <h1>Welcome to React JS</h1>
      <p>My first React application is running.</p>
      <button>Get Started</button>
    </div>
  );
}

export default App;

Explanation

  • function App() declares a React function component.
  • return provides the JSX describing the UI.
  • displays the main heading.

  • displays a paragraph.

  • export default App allows the component to be imported into another file.

Save the file and view the page in your browser. Vite normally refreshes the development page when you save changes.


9. Add CSS to Your React Application

CSS makes the application more attractive by controlling colors, spacing, fonts, and layout.

Example of App.css

#root {
  max-width: 900px;
  margin: 0 auto;
  padding: 40px 20px;
  font-family: Arial, sans-serif;
  text-align: center;
}

h1 {
  color: #2563eb;
}

p {
  color: #444;
  font-size: 18px;
}

button {
  padding: 10px 18px;
  border: none;
  border-radius: 6px;
  background: #2563eb;
  color: white;
  cursor: pointer;
}

button:hover {
  background: #1d4ed8;
}

Import the stylesheet into App.jsx by adding this line at the top:

import "./App.css";

Save the files to see the styles applied in the browser.


10. Add Interactivity Using useState

React components can respond to user actions using event handlers and state. The useState() Hook allows a component to store a value and update the UI when that value changes.

Example: Counter Application

import { useState } from "react";
import "./App.css";

function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>React Counter</h1>
      <p>Current Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
      <button onClick={() => setCount(count - 1)}>
        Decrease
      </button>
      <button onClick={() => setCount(0)}>
        Reset
      </button>
    </div>
  );
}

export default App;

Explanation

  • useState(0) initializes the count to zero.
  • count contains the current state value.
  • setCount updates the state.
  • onClick handles button clicks.
  • {count} displays the current value in the UI.

When a user clicks a button, the state changes and React updates the UI to reflect the new value.


11. Important npm Commands in a React Project

Command Purpose
node -v Checks the installed Node.js version.
npm -v Checks the installed npm version.
npm create vite@latest my-react-app -- --template react Creates a new React project using Vite.
cd my-react-app Moves into the project directory.
npm install Installs project dependencies.
npm run dev Starts the Vite development server.
npm run build Builds the application for production.
npm run preview Locally previews the production build using Vite.

Available scripts are listed in the project's package.json. If a command is missing, check that file for the scripts configured in your project.


12. How to Build a React Application for Production

After development and testing, you can create a production build of your application.

Step 1: Run the Build Command

npm run build

Vite generates optimized production files, usually in the dist/ directory.

Step 2: Preview the Production Build

npm run preview

Open the local URL displayed in the terminal to test the production build. This preview is intended for local verification, not as a production hosting server.

Step 3: Deploy the Build

Upload the generated dist/ files to a suitable static hosting service, or follow the deployment instructions for your chosen framework or hosting platform.

Before deploying, verify the application, test its main interactions, and check for console errors.


13. Common Errors When Creating a React Application

Error or Problem Possible Solution
node is not recognized Install Node.js, reopen the terminal, and verify the PATH configuration.
npm is not recognized Check the Node.js installation and ensure npm is available in PATH.
Missing dependencies Run npm install in the project directory.
Wrong directory Use cd my-react-app to enter the correct folder.
Development server does not start Read the terminal error, check Node.js compatibility, and verify the project's scripts.
Blank browser page Check the browser console, component imports, and the root element in index.html.
JSX syntax error Check closing tags, brackets, parentheses, and component syntax.
CSS is not applied Verify the stylesheet path and its import statement.
Port already in use Use the alternative local URL shown by the development server or free the occupied port.
Component is not displayed Check the export statement, import path, and whether the component is rendered.

14. Create React App vs Vite

The phrase “Create React App” can refer generally to creating a React application or specifically to the older tool named Create React App. These are not the same thing.

Basis Create React App (CRA) Vite
Purpose Older tool for setting up React projects. Modern build tool that supports React templates.
Status Deprecated and in long-term stasis. Actively maintained build tool.
Development command Typically npm start. Typically npm run dev.
Production build Typically npm run build. Typically npm run build.
Typical output folder build/ dist/
Recommended use Useful for understanding older tutorials and existing projects. Useful for learning React from scratch and creating client-side React projects.

Important: React's official documentation marks Create React App as deprecated and does not recommend it for new production applications. For many new applications, consider a recommended React framework; for learning React fundamentals, Vite is a practical option. React's official guidance on creating an app.


15. Best Practices for Creating a React Application

  • Use clear and meaningful component names.
  • Divide complex interfaces into small, reusable components.
  • Keep components focused on a clear responsibility.
  • Use state and props to manage UI data.
  • Avoid direct DOM manipulation when React state and props can handle the update.
  • Keep related components and styles organized.
  • Use reusable functions and components to avoid unnecessary code duplication.
  • Check the browser console and terminal for errors.
  • Test the application in more than one browser when appropriate.
  • Use a suitable framework or architecture when the application needs routing, data fetching, server rendering, or other production features.
  • Never commit passwords, private API keys, or other secrets to a public repository.

16. Mini Project: Personal Profile Application

Build a simple profile page to practice creating a React component, writing JSX, adding CSS, and displaying data.

App.jsx

import "./App.css";

function App() {
  const student = {
    name: "Aarav Sharma",
    course: "React JS",
    goal: "Become a Frontend Developer"
  };

  return (
    <div className="profile">
      <h1>Student Profile</h1>
      <h2>{student.name}</h2>
      <p>Course: {student.course}</p>
      <p>Career Goal: {student.goal}</p>
    </div>
  );
}

export default App;

App.css

.profile {
  max-width: 500px;
  margin: 40px auto;
  padding: 24px;
  border: 1px solid #ddd;
  border-radius: 12px;
  font-family: Arial, sans-serif;
}

.profile h1 {
  color: #2563eb;
}

.profile p {
  line-height: 1.6;
}

Project Tasks

  1. Create the React project using Vite.
  2. Replace the starter component with the profile component.
  3. Add CSS to style the profile page.
  4. Change the sample student's name and course.
  5. Add a button and use state to show or hide additional profile details.
  6. Run npm run build to verify that the project builds successfully.

17. Frequently Asked Interview Questions

Q1. What is a React application?

A React application is a user interface application built using React components and related JavaScript tools.

Q2. What is Vite?

Vite is a frontend build tool that provides a development server and production build process for projects such as React applications.

Q3. Why do we need Node.js to create a React project?

Node.js provides the runtime used by development tools and package managers. It allows tools such as npm and Vite to run locally.

Q4. What is npm?

npm is a package manager commonly used to install and manage JavaScript project dependencies and run scripts.

Q5. What is JSX?

JSX is a syntax extension that lets developers write markup-like expressions within JavaScript code to describe a UI.

Q6. What is the purpose of App.jsx?

In a typical Vite React starter project, App.jsx contains the main App component and its UI.

Q7. What is the purpose of main.jsx?

It is typically the entry point that creates the React root and renders the App component into an HTML element.

Q8. How do you run a Vite React application?

Run npm install to install dependencies and npm run dev to start the development server.

Q9. How do you create a production build?

Run npm run build. In a standard Vite project, the generated files are placed in the dist/ directory.

Q10. Is Create React App still recommended for new projects?

No. The React team has deprecated Create React App. Consider a recommended React framework or a tool such as Vite when starting a suitable project from scratch.


18. Quick Revision Notes

  • React is a JavaScript library for building user interfaces.
  • Node.js and npm are commonly used to set up and manage local React projects.
  • Vite is one option for creating a React project from scratch.
  • npm create vite@latest my-react-app -- --template react creates a starter project.
  • npm install installs dependencies.
  • npm run dev starts the development server.
  • App.jsx usually contains the main App component.
  • main.jsx typically renders the App component into the root element.
  • useState() helps manage component state.
  • npm run build creates a production build.
  • Create React App is deprecated; avoid choosing it for a new production application.

19. Conclusion

Creating a React application involves preparing the development environment, generating a project, installing dependencies, building components, adding styles, testing the UI, and creating a production build. For learning React fundamentals, Vite provides a straightforward way to get started. As an application grows, you can add routing, API integration, reusable components, testing, and other tools as needed.

Learn React JS with JustAcademy

Explore the JustAcademy React JS Training Course to learn React concepts and develop practical web application skills.

Want to learn more about the course? Register for the React JS Course Demo.

Official Learning Resources

whatsapp